//
//  IndexSegment.m
//  yigou
//
//  Created by SunChao on 17/1/13.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "CJNaviView.h"

#define kSelectedColor [UIColor colorWithRed:14/255.0 green:161/255.0 blue:182/255.0 alpha:1]
#define kNormalColor   [UIColor whiteColor]
#define UIColorFromHex(s)  [UIColor colorWithRed:(((s & 0xFF0000) >> 16))/255.0green:(((s &0xFF00) >>8))/255.0 blue:((s &0xFF))/255.0alpha:1.0]


@implementation CJNaviButton

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        CGFloat lineWidth = 3;
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, frame.size.height - lineWidth, frame.size.width, lineWidth)];
        // 设置初始状态
        lineView.backgroundColor = kNormalColor;
        _lineView = lineView;
        [self setTitleColor:kNormalColor forState:UIControlStateNormal];
        self.titleLabel.font = [UIFont systemFontOfSize:14];
        [self setBackgroundColor:[UIColor whiteColor]];
        [self addSubview:lineView];
        
    }
    return self;
}



@end



@implementation CJNaviView
/**
 *  init方法
 *
 *  @param titles   title数组 :@[@"选项1",@"选项2"]
 *  @param frame    整个naviView frame
 *  @param delegate 设置代理
 *
 *  @return CJNaviView实例
 */
- (instancetype)initWithNumberOfTitles:(NSArray *)titles andFrame:(CGRect)frame delegate:(id<CJNaviViewDelegate>)delegate selectedBtn:(NSInteger)buttonTag{
    if (self = [super initWithFrame:frame]) {
        // 设置代理
        self.delegate = delegate;
        CGFloat buttonWidth = ScreenWidth / titles.count;
        CJNaviButton *cjBtn;
        for (int i = 0; i < titles.count; i ++) {
            cjBtn = [[CJNaviButton alloc] initWithFrame:CGRectMake(i *buttonWidth, 0, buttonWidth, frame.size.height)];
        // 设置对应的tag
            cjBtn.tag = i;
            [cjBtn setTitle:titles[i] forState:UIControlStateNormal];
            [cjBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [cjBtn addTarget:self action:@selector(A_choosed:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:cjBtn];
            [cjBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            cjBtn.lineView.backgroundColor = kSelectedColor;
            [_lastClickButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        CJNaviButton *button = [cjBtn viewWithTag:buttonTag];
        cjBtn.lineView.backgroundColor = kNormalColor;
        _lastClickButton = button;
    }
    
    return self;

}

- (void)A_choosed:(CJNaviButton *)button{
    // 连续点击同一个不响应回调
//    if (_lastClickButton != button) {
        // 设置状态
//        14 161 182
        _lastClickButton.lineView.backgroundColor = kNormalColor;
        _lastClickButton = button;
        // 回调 可用block
        if ([self.delegate respondsToSelector:@selector(D_selectedTag:)]) {
            [self.delegate D_selectedTag:button.tag];
        }
//    }
}
@end
